package com.x.gzcrm.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.x.gzcrm.mapper.RoleMapper;
import com.x.gzcrm.model.Role;
import com.x.gzcrm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    RoleMapper roleMapper;
    @Override
    public List<Role> findAllRoles() {
        return roleMapper.findAllRoles();
    }

    @Override
    public void save(Role role, String ids) {
        if(role.getId() == 0){
            System.out.println("插入角色");
            // 1.先保存角色(sys_role)
            roleMapper.insert(role);
            //System.out.println("插入后的角色:" + role);
        }
        else{
            System.out.println("修改角色");
            roleMapper.update(role);
            //1.修改角色的名称和描述
           //2.把旧的权限全部删除
            roleMapper.deletePermissionByRoleId(role.getId());
        }

        //System.out.println(1/0);
//        保存角色权限表（sys_role_permission）1,5,6,7,8,9,10,11,12,2,13
//        5,1
//        5,5
//        5,6

        //这里是一条一条插入 不高效
//        String [] idsArr = ids.split(",");
//        for(String pmsId : idsArr){
//            roleMapper.insertRolePermission(role.getId(),Integer.parseInt(pmsId));
//        }
        // 批处理插入高效
        roleMapper.insertRolePermissionBatch(role.getId(),ids);

    }

    @Override
    public Role findByRoleId(Integer roleId) {
        return roleMapper.findByRoleId(roleId);
    }

    @Override
    public String findPermissionIdsStrByRoleId(Integer roleId) {
        List<Integer> idsList = roleMapper.findPermissionIdsByRoleId(roleId);
        System.out.println(idsList);
        if(idsList.size() == 0) return "";

        StringBuffer sb = new StringBuffer("");
        for(Integer id :idsList){
            sb.append(id).append(",");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }

    @Override
    public void delete(Integer roleId) {
        roleMapper.deletePermissionByRoleId(roleId);
        roleMapper.deleteRole(roleId);
    }

    /**
     * 使用PageHelper实现分页
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Role> findPageInfo(int page, int pageSize) {
        //int offset, int limit
        PageHelper.offsetPage((page-1)*pageSize,pageSize);
        PageInfo<Role> info = new PageInfo<>(roleMapper.findAllRoles());
        return info;
    }
}